/**
 * Calendar
 * calendar.controllers
 * 日程模块控制器
 * @P.s 日程模块用到的 cEvts 指代日程记录，跟 js 意义的事件没有任何关系
 */

angular.module('calendar.controllers', [])

/**
 * @ngdoc controller
 * @name CalendarCtrl
 * @module calendar.controllers
 * @description
 *   日程列表页页面控制器
 */
  .controller('CalendarCtrl', function($scope, $ionicScrollDelegate, $ionicLoading, Calendar, CalendarUtil ,User, Utils) {
    $ionicLoading.show();
    User.getAuthority().success(function(res){
      if(res.isSuccess){
        if(res.data.calendar){
          $scope.title = '我的日程';

          $scope.calendars = [];
          $scope.calendars.loaded = false;

          // 初始化控制器时，自动获取数据, 自动获取下月和本月的日程
          Calendar.fetch(CalendarUtil.getDateRange())
            .success(function(data){
              $scope.calendars = CalendarUtil.groupEvents(data.events);
              $scope.calendars.loaded = true;
            });

          $scope.$on('$ionicView.beforeLeave', function() {
            $ionicScrollDelegate.scrollTop();
          });
        } else{
          Utils.promptNoPermission();
        }
      }
    }
    ).finally($ionicLoading.hide)
  })

/**
 * @ngdoc controller
 * @name CalendarCreateCtrl
 * @module calendar.controllers
 * @description
 *   日程新建页页面控制器
 */
  .controller('CalendarCreateCtrl', function($scope, $state, $ionicHistory, $ionicLoading, Calendar, CalendarUtil, DAY_MILLISECOND){

    $scope.title = "新建日程";

    var date = CalendarUtil.getCurrentDateTime();

    // 日程默认数据
    $scope.calendar = {
      isalldayevent: false,
      editable: true,
      category: 0,

      startDate: date,
      endDate: new Date(+date + DAY_MILLISECOND),

      startTime: date,
      endTime: new Date(+date + DAY_MILLISECOND / 12)
    };

    //开启全天模式时，结束日期应比开始日期晚一天
    $scope.$watch('calendar.startDate', function (newStartDate) {
      if($scope.calendar.isalldayevent){
        $scope.calendar.endDate = new Date( +newStartDate + DAY_MILLISECOND)
      }
    });

    // 表示表单是否正处于提交状态
    function resetSubmit(){
      $scope.isSubmiting = false;
      $ionicLoading.hide();
    }

    // 正在提交表单
    function doSubmit() {
      $scope.isSubmiting = true;
      $ionicLoading.show({ delay: 300 });
    }

    $scope.submit = function(){
      console.log($scope.calendar)
      doSubmit();
      Calendar.create(Calendar.formatSubmitData($scope.calendar))
        .success(function(){
          $ionicHistory.clearCache().then(function(){
            $state.go('calendar');
          });
          // $state.go('calendar');
        })
        .finally(resetSubmit);
    }
  }
)

/**
 * @ngdoc controller
 * @name CalendarDetailCtrl
 * @module calendar.controllers
 * @description
 *   日程详情页, 日程模块详细页与编辑功能结合在一起
 */
  .controller('CalendarDetailCtrl', function($scope, $state, $timeout, $stateParams, $ionicPopup, $ionicHistory, $ionicLoading, Calendar, CalendarUtil, IbPopup){

    $scope.title = "编辑日程";

    // 获取当前 id 对应的日程数据
    Calendar.get($stateParams.calendarId)
      .success(function(res){
        if(res && res != 'null') {
          // 所以目前要格式化为期望格式
          $scope.calendar = CalendarUtil.parseTime(res);
        } else {
          $ionicPopup.alert({
            title: '提示',
            template: '找不到相关日程数据，将返回日程列表'
          })
            .then(function(){
              $state.go('calendar')
            })
        }
      });

    // 表示表单是否正处于提交状态
    function resetSubmit(){
      $scope.isSubmiting = false;
      $ionicLoading.hide();
    }

    // 正在提交表单
    function doSubmit() {
      $scope.isSubmiting = true;
      $ionicLoading.show({ delay: 300 });
    }

    // 保存
    $scope.submit = function(){
      doSubmit();
      Calendar.update(Calendar.formatSubmitData($scope.calendar))
        .success(function(){
          $ionicHistory.clearCache().then(function() {
            $state.go('calendar');
          });
        })
        .finally(resetSubmit);
    }

    // 删除
    $scope.remove = function(){
      doSubmit();
      Calendar.removeOne($scope.calendar.calendarid)
        .success(function(){
          IbPopup.tip('删除成功!').then(function() {
            $ionicHistory.clearCache().then(function() {
              $state.go('calendar');
            });
          });
        })
        .finally(resetSubmit);
    }

    // 完成日程
    $scope.finish = function(){
      if($scope.calendar.status == '0') {
        doSubmit();
        var parsed = CalendarUtil.parseTime($scope.calendar);

        Calendar.finish(Calendar.formatSubmitData(parsed))
          .success(function(){
            $ionicHistory.clearCache();
            $scope.calendar.status = '1';
          })
          .finally(resetSubmit);
      }

    }

    // 取消完成日程
    $scope.unfinish = function(){
      if($scope.calendar.status == '1') {
        doSubmit();
        var parsed = CalendarUtil.parseTime($scope.calendar);

        Calendar.unfinish(Calendar.formatSubmitData(parsed))
          .success(function(){
            $ionicHistory.clearCache();
            $scope.calendar.status = '0';
          })
          .finally(resetSubmit);
      }
    }
  }
)

